package cn.crap.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AESUtil {
	//public static final String VIPARA = "0102030405060708";  
	public static byte[] iv = {1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8};
	public static final String bm = "utf-8";
	
	public static String encrypt(String dataPassword, String cleartext)  
	        throws Exception {  
	    IvParameterSpec zeroIv = new IvParameterSpec(iv);  
	    SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(bm), "AES");  
	    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
	    cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);  
	    byte[] encryptedData = cipher.doFinal(cleartext.getBytes(bm));  
	  
	    return Base64.encodeBase64String(encryptedData);
	}  
	  
	public static String decrypt(String dataPassword, String encrypted)  
	        throws Exception {  
		byte[] byteMi = Base64.decodeBase64(encrypted);
	    IvParameterSpec zeroIv = new IvParameterSpec(iv);  
	    SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(bm), "AES");  
	    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
	    cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);  
	    byte[] decryptedData = cipher.doFinal(byteMi);  
	  
	    return new String(decryptedData,bm);  
	}
	
	/**将16进制转换为二进制 
	 * @param hexStr 
	 * @return 
	 */  
	public static byte[] parseHexStr2Byte(String hexStr) {  
	        if (hexStr.length() < 1)  
	                return null;  
	        byte[] result = new byte[hexStr.length()/2];  
	        for (int i = 0;i< hexStr.length()/2; i++) {  
	                int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
	                int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);  
	                result[i] = (byte) (high * 16 + low);  
	        }  
	        return result;  
	}
	
	/**将二进制转换成16进制 
	 * @param buf 
	 * @return 
	 */  
	public static String parseByte2HexStr(byte buf[]) {  
	        StringBuffer sb = new StringBuffer();  
	        for (int i = 0; i < buf.length; i++) {  
	                String hex = Integer.toHexString(buf[i] & 0xFF);  
	                if (hex.length() == 1) {  
	                        hex = '0' + hex;  
	                }  
	                sb.append(hex.toUpperCase());  
	        }  
	        return sb.toString();  
	}
	
	public static void main(String[] args) {
		String str = "imei=00&imsi=00&mac=00&ua=ZTE Q505T&appid=1&apptype=1&pf=00&vv=00&v=1.0.0&ckid=&uuid=&nw=3&ua2=&yys=&dafangsong=1444632834049";
		//String str2 = "";
		String pwd = "DFF2A84A2844BD79";
		
		try {
			String jiami = encrypt(pwd,str);
			System.out.println(jiami);
			System.out.println(decrypt(pwd,jiami));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
